package org.colcon.web.model.vote;

import org.colcon.web.model.CLI;
import org.colcon.web.model.Decision;
import org.colcon.web.model.Model;
import org.colcon.web.model.Title;
import org.colcon.web.model.decision.NullDecision;
import org.colcon.web.model.framework.IBallot;
import org.colcon.web.model.framework.IDecision;
import org.colcon.web.model.framework.ITitle;
import org.colcon.web.model.framework.IUser;

public class ElectionVote extends MultiChoiceVote
{
	private static final long serialVersionUID = -6556328392839973525L;

	private int threshold;
	
	private IUser[] candidates;
	private ITitle title;
	
	public ElectionVote()
	{
		this(Model.NULL, Model.NULL, 0, 0, 0, new String[0], new Title(), new IUser[0]);
	}
	
	//TODO: change all args to String
	public ElectionVote(String group, String id, int length, int quorum, int threshold, String[] titles, ITitle title, IUser[] candidates) 
	{
		super(group, id, length, quorum, titles, getChoices(title, candidates));
		
		this.threshold = threshold;
		
		this.candidates = candidates;
		this.title = title;
	}
	
	public double getThreshold()
	{
		return threshold;
	}
	
	public IUser[] getCandidates()
	{
		return candidates;
	}
	
	public String getText()
	{
		return "This winner of this vote will gain the following title: " + title.getLongName();
	}
	
	public IDecision getDecision() 
	{
		if(getWinner() == -1)
			return new NullDecision(getGroup());
		
		return getChoices()[getWinner()];
	}
	
	public String getWinnerName()
	{
		int winner = getWinner();
		
		if(winner == -1)
			return "";
		else
			return candidates[getWinner()].getId();
	}
	
	public int getWinner()
	{
		boolean draw = false;
		int winner = 0;
		
		for(int i = 1; i < getChoices().length; i++)
		{
			if(getVotes(i) > getVotes(winner))
			{
				winner = i;
				draw = false;
			}
			else if(getVotes(i) == getVotes(winner))
			{
				draw = true;
			}
		}
		
		if(!draw && getVotes(winner) >= threshold)
			return winner;
		else
			return -1;
	}
	
	public int getVotes(int i)
	{
		return getVotes(candidates[i].getId());
	}
	
	public int getVotes(String str)
	{
		int count = 0;
		
		for(IBallot ballot : getBallots())
			if(ballot.getValue().equals(str))
				count++;
				
		return count;
	}
	
	private static IDecision[] getChoices(ITitle title, IUser[] candidates)
	{
		IDecision[] choices = new IDecision[candidates.length];
		
		for(int i = 0; i < choices.length; i++)
			choices[i] = new Decision(title.getGroup(), CLI.ASSIGN + " " + title.getPath() + " -user " + candidates[i]);
		
		return choices;
	}
}
